<template>
    <div>
        <!-- 面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片视图-->
        <el-card>
            <!--添加角色按钮-->
            <el-row>
                <el-col><el-button type="primary" @click="addRoleBtn">添加角色</el-button></el-col>
            </el-row>
            <!--角色列表区域-->
            <el-table :data="rolesList" border stripe>
                <!--展开列-->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id"
                        :class="['bd-bottom', i1 === 0? 'bd-top' : '', 'vcenter']">
                            <!--渲染一级权限-->
                            <el-col :span="5">
                                <el-tag closable @close="removeRights(scope.row, item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--渲染二级权限-->
                            <el-col :span="19">
                                <!--通过for循环嵌套渲染二级权限-->
                                <el-row v-for="(item2, i2) in item1.children" :key="item2.id"
                                :class="['bd-top', i2 === 0? '' : 'bd-top', 'vcenter']">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRights(scope.row, item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id"
                                        closable @close="removeRights(scope.row, item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!--索引列-->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="320px">
                    <template slot-scope="scope">
                        <!--{{scope.row.id}}-->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole(scope.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini"
                        @click="showSettingRightsDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!--添加角色-->
        <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="resetAddForm">
            <el-form label-width="80px" :model="addRoleForm" ref="addRoleRef"
         :rules="addRoleRules">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
        </el-dialog>
        <!--编辑修改角色-->
        <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="50%">
            <el-form label-width="80px" :model="editRoleForm">
                <el-form-item label="角色名称">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRoleCommit">确 定</el-button>
        </span>
        </el-dialog>
        <!--分配权限对话框-->
        <el-dialog title="分配权限" :visible.sync="settingRightsDialog" width="50%" @close="settingRightsDialogClose">
        <!--树形控件-->
        <el-tree :data="rightsList" :props="treeProps" node-key="id" show-checkbox default-expand-all
        :default-checked-keys="defKeys" ref="rightsRefs"></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="settingRightsDialog = false">取 消</el-button>
            <el-button type="primary" @click="divideRights">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        return {
            // 所有角色列表
            rolesList: [],
            // 添加角色
            addRoleForm: {
                roleName: '',
                roleDesc: ''
            },
            // 控制添加角色对话框的显示与隐藏
            addRoleDialogVisible: false,
            // 编辑用户表单
            editRoleForm: {},
            // 编辑角色对话框的显示与隐藏
            editRoleDialogVisible: false,
            // 权限列表
            rightsList: [],
            // 分配权限对话框的显示与隐藏
            settingRightsDialog: false,
            // 树形控件属性绑定对象
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            // 默认选中节点id数组
            defKeys: [],
            // 即将分配角色的id
            roleId: '',
            // 添加角色规则
            addRoleRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: false, message: '请输入角色描述', trigger: 'blur' },
                    { max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    created () {
        this.getRolesList()
    },
    methods: {
        async getRolesList () {
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) {
                return this.$message.error('获取用户角色失败')
            }
            this.rolesList = res.data
        },
        addRoleBtn () {
            this.addRoleDialogVisible = true
        },
        // 添加角色
        addRole () {
            this.$refs.addRoleRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post('roles', {
                    roleName: this.addRoleForm.roleName,
                    roleDesc: this.addRoleForm.roleDesc
                })
                    if (res.meta.status !== 201) {
                        return this.$message.error('添加角色失败')
                    }
                    this.$message.success('添加角色成功')
                    this.getRolesList()
                    this.addRoleDialogVisible = false
            })
        },
        // 添加角色表单重置
        resetAddForm () {
            this.$refs.addRoleRef.resetFields()
        },
        // 编辑修改角色
        async editRole (id) {
            const { data: res } = await this.$http.get('roles/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error('获取角色失败')
            }
            this.roleId = id
            this.editRoleForm = res.data
            console.log(this.editRoleForm)
            this.editRoleDialogVisible = true
        },
        // 修该角色信息
        async editRoleCommit () {
            const { data: res } = await this.$http.put(`roles/${this.roleId}`, {
                roleName: this.editRoleForm.roleName,
                roleDesc: this.editRoleForm.roleDesc
            })
            if (res.meta.status !== 200) {
                return this.$message.error('编辑角色失败')
            }
            this.getRolesList()
            this.editRoleDialogVisible = false
        },
        // 删除角色
        async deleteRole (id) {
            const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (result === 'cancel') return this.$message.info('已取消删除操作')
            const { data: res } = await this.$http.delete('roles/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error('删除角色失败')
            }
            this.$message.success('删除角色成功')
            this.getRolesList()
        },
        // 删除对应权限
        async removeRights (roles, rightsId) {
            // 询问是否删除
            const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err => err)
        if (result === 'cancel') {
            this.$message.info('已取消删除操作')
        }
        const { data: res } = await this.$http.delete(`roles/${roles.id}/rights/${rightsId}`)
        if (res.meta.status !== 200) {
            return this.$message.error('取消权限失败')
        }
        // 会导致页面重新渲染,expand标签要重新展开
        // this.getRolesList()
        roles.children = res.data
        },
        // 设置分配权限对话框
        async showSettingRightsDialog (role) {
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) {
                return this.$message.error('获取权限列表失败')
            }
            // 将获取数据保存到data中
            this.rightsList = res.data
            // console.log(this.rightsList)
            // 将默认节点添加到分配权限对话框中
            this.getLeafKeys(role, this.defKeys)
            // 将角色id保存到data中
            this.roleId = role.id
            this.settingRightsDialog = true
        },
        // 通过递归获取角色下三级权限并保存到数组中
        getLeafKeys (node, arr) {
            // 如果当前节点不包含children属性，则证明时三级节点
            if (!node.children) {
                return arr.push(node.id)
            }
            node.children.forEach(item => {
                this.getLeafKeys(item, arr)
            })
        },
        // 监听对话框关闭事件
        settingRightsDialogClose () {
            this.defKeys = []
        },
        // 为角色分配权限
        async divideRights () {
            const keys = [...this.$refs.rightsRefs.getHalfCheckedKeys(),
            ...this.$refs.rightsRefs.getCheckedKeys()]
            // console.log(keys)
            const idStr = keys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
            if (res.meta.status !== 200) {
                return this.$message.error('分配权限失败')
            }
            this.$message.success('分配权限成功')
            this.getRolesList()
            this.settingRightsDialog = false
        }
    }
}
</script>

<style lang="less" scoped>
    .el-row {
        margin-bottom: 0;
    }
    .el-tag {
        margin: 7px;
    }
    .bd-top {
        border-top: 1px solid #eee;
    }
    .bd-bottom {
        border-bottom: 1px solid #eee;
    }
    /*纵向居中*/
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>
